package com.szqhyxj.youxiangju.biz.realNameAuth.idcard;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

import com.szqhyxj.youxiangju.biz.core.ImageUploadResult;
import com.szqhyxj.youxiangju.biz.core.ImageUploader;
import com.szqhyxj.youxiangju.biz.realNameAuth.RealNameModel;
import com.szqhyxj.youxiangju.sys.BaseResult;
import com.szqhyxj.youxiangju.sys.util.BitmapCompressFile;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class IDCardAuthPresenter implements IDCardAuthContract.Presenter {

    private IDCardAuthContract.View view;

    private List<Disposable> disposables = new ArrayList<>();

    IDCardAuthPresenter(IDCardAuthContract.View view) {
        this.view = view;
        this.idCardEntity = new IDCardEntity();
    }

    private IDCardEntity idCardEntity;


    @Override
    public void takePhotoForFace(Context context) throws IOException {
        File faceFile = RealNameModel.createImageFile(context);
        this.idCardEntity.setFace(faceFile);
        view.navToTakePhotoFace(faceFile);
    }

    @Override
    public void takePhotoForBack(Context context) throws IOException {
        File faceFile = RealNameModel.createImageFile(context);
        this.idCardEntity.setBack(faceFile);
        view.navToTakePhotoBack(faceFile);
    }

    @Override
    public void selectFromGalleryForFace() {
        view.navToGalleryForFace();
    }

    @Override
    public void selectFromGalleryForBack() {
        view.navToGalleryForBack();
    }

    @Override
    public void idcardFaceFromTakePhoto(Context context) throws IOException {
        view.previewFace(this.idCardEntity.getFace());
        //  ocrIdcardFace(this.idCardEntity.getFace());
        uploadIdCardFace(this.idCardEntity.getFace());
    }

    @Override
    public void idcardBackFromTakePhoto(Context context) throws IOException {
        view.previewBack(this.idCardEntity.getBack());
        //ocrIdcardBack(this.idCardEntity.getBack());
        uploadIDCardBack(this.idCardEntity.getBack());
    }

    @Override
    public void idcardBackFromGallery(File file) {
        view.previewBack(file);
        this.idCardEntity.setBack(file);
        //ocrIdcardBack(this.idCardEntity.getBack());
        uploadIDCardBack(this.idCardEntity.getBack());
    }

    @Override
    public void setCommit() {
        view.showCommit();
    }

    @Override
    public void setEncommit() {
        view.showEncommit();
    }

    private void checkRegisterEnable() {
        if (idCardEntity.valid()) {
            view.showCommit();

        } else {
            view.showEncommit();

        }
    }

    @Override
    public void idcardFaceFromGallery(File file) {
        view.previewFace(file);
        this.idCardEntity.setFace(file);
        //ocrIdcardFace(this.idCardEntity.getFace());
        uploadIdCardFace(this.idCardEntity.getFace());
    }

    private void ocrIdcardFace(final File file) {
        view.showLoading("正在识别...");
        Disposable disposable = RealNameModel
                .ocrIDCardFace(file)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Consumer<BaseResult<IDCardFaceInfo>>() {
                            @Override
                            public void accept(BaseResult<IDCardFaceInfo> ocrResult) {
                                view.dismissLoading();
                                if (ocrResult.businessLogicSuccess()) {
                                    Log.d("namename", ocrResult.getData().getName());
                                    idCardEntity.setUsername(ocrResult.getData().getName());
                                    idCardEntity.setIdCard(ocrResult.getData().getIdCardNo());
                                    view.showIDCardFace(ocrResult.getData());
                                    view.enshowOCRTip();

                                    view.showOCRName(ocrResult.getData().getName());
                                    view.showOCRIdno(ocrResult.getData().getIdCardNo());

                                    uploadIdCardFace(file);
                                } else {
                                    view.showFace();
                                    view.showOCRTip(ocrResult.getMessage());
                                    view.showOcrFail(ocrResult.getMessage());

                                }
                            }
                        },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) {
                                view.dismissLoading();
                                view.showFace();
                                view.showOCRTip(throwable.getMessage());
                                Log.e("error:", throwable.getMessage());
                                view.showOcrFail(throwable.getMessage());
                            }
                        });
        disposables.add(disposable);
    }

    private void ocrIdcardBack(File file) {
        view.showLoading("正在识别...");
        Disposable disposable = RealNameModel
                .ocrIDCardBack(file)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Consumer<BaseResult<IDCardBackInfo>>() {
                            @Override
                            public void accept(BaseResult<IDCardBackInfo> ocrResult) {
                                view.dismissLoading();
                                if (ocrResult.businessLogicSuccess()) {
                                    view.showIDCardBack(ocrResult.getData());
                                    view.enshowOCRTip();
                                    idCardEntity.setCertStateDate(ocrResult.getData().getStartDate());
                                    idCardEntity.setCertExpireDate(ocrResult.getData().getEndDate());
                                    String date = "";
                                    SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
                                    SimpleDateFormat parse = new SimpleDateFormat("yyyyMMdd");
                                    try {
                                        String startDate = df.format(parse.parse(ocrResult.getData().getStartDate()));
                                        String endDate = df.format(parse.parse(ocrResult.getData().getEndDate()));
                                        date = startDate + "-" + endDate;
                                        view.showOCRValidity(date);
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }

                                    view.showOCRValidity(date);
                                    uploadIDCardBack(file);
                                } else {
                                    view.showBack();
                                    view.showOCRTip(ocrResult.getMessage());
                                    view.showOcrFail("111111111" + ocrResult.getMessage());

                                }
                            }
                        },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) {
                                view.dismissLoading();
                                view.showBack();
                                view.showOCRTip(throwable.getMessage());
                                view.showOcrFail("22222222222" + throwable.getMessage());

                            }
                        }
                );
        disposables.add(disposable);
    }



    private void uploadIdCardFace(File file) {
        File tfile =BitmapCompressFile.compressFile(file);
        view.showLoading("正在上传...");
                Disposable disposable = ImageUploader
                .uploadIdcardFace(tfile)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Consumer<BaseResult<ImageUploadResult>>() {
                            @Override
                            public void accept(BaseResult<ImageUploadResult> uploadResult) {
                                view.dismissLoading();
                                if (uploadResult.businessLogicSuccess()) {
                                    view.showInfo();
                                    idCardEntity.setFaceUrl(uploadResult.getData().getFileUrl());
                                    view.showIDCardFaceUploadSuccess(uploadResult.getData().getFileUrl());
                                    view.uploadSuccessFace();
                                    checkRegisterEnable();
                                } else {
                                    view.showIDCardFaceUploadFail(uploadResult.getMessage());
                                }
                                tfile.delete();
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) {
                                view.dismissLoading();
                                view.showIDCardFaceUploadFail(throwable.getMessage());
                                tfile.delete();
                            }
                        }
                );
        disposables.add(disposable);
    }

    private void uploadIDCardBack(File file) {
        view.showLoading("正在上传...");
        File tfile =BitmapCompressFile.compressFile(file);
        Disposable disposable = ImageUploader
                .uploadIdcardBack(tfile)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Consumer<BaseResult<ImageUploadResult>>() {
                            @Override
                            public void accept(BaseResult<ImageUploadResult> uploadResult) {
                                view.dismissLoading();
                                if (uploadResult.businessLogicSuccess()) {
                                    view.showInfo();
                                    idCardEntity.setBackUrl(uploadResult.getData().getFileUrl());
                                    view.showIDCardFaceUploadSuccess(uploadResult.getData().getFileUrl());
                                    view.uploadSuccessBack();
                                    checkRegisterEnable();
                                } else {
                                    view.showIDCardFaceUploadFail(uploadResult.getMessage());
                                }
                                tfile.delete();
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) {
                                view.dismissLoading();
                                view.showIDCardFaceUploadFail(throwable.getMessage());
                                tfile.delete();
                            }
                        }
                );
        disposables.add(disposable);
    }


    @Override
    public void setName(String s) {
        idCardEntity.setUsername(s);
        //   view.showOCRName(s);
        checkRegisterEnable();
    }

    @Override
    public void setIdCard(String s) {
        idCardEntity.setIdCard(s);
        //  view.showOCRIdno(s);
        checkRegisterEnable();
    }


    @Override
    public void setStartDate(String s) {
        idCardEntity.setCertStateDate(s);
        // view.showStartDate(s);
        checkRegisterEnable();
    }

    @Override
    public void setEndDate(String s) {
        //   view.showEndDate(s);
        idCardEntity.setCertExpireDate(s);
        checkRegisterEnable();
    }

    @Override
    public void request() {
        view.showLoading("正在加载...");
        RealNameModel.queryIdCard()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResult<IDCardEntity>>() {
                    @Override
                    public void accept(BaseResult<IDCardEntity> requestEntityBaseResult) throws Exception {
                        view.dismissLoading();
                        if (requestEntityBaseResult.businessLogicSuccess()) {
                            if (requestEntityBaseResult == null) {
                                view.enshowInfo();
                            } else {
                                view.showInfo();
                                view.flagUrl();
                                view.showFaceUrl(requestEntityBaseResult.getData().getFaceUrl());
                                view.showBackUrl(requestEntityBaseResult.getData().getBackUrl());
                                view.showOCRName(requestEntityBaseResult.getData().getUsername());
                                view.showOCRIdno(requestEntityBaseResult.getData().getIdCard());
                                String date = "";
                                SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
                                SimpleDateFormat parse = new SimpleDateFormat("yyyy-MM-dd");
                                SimpleDateFormat parse1 = new SimpleDateFormat("yyyyMMdd");
                                try {
                                    String startDate = df.format(parse.parse(requestEntityBaseResult.getData().getCertStateDate()));
                                    String endDate = df.format(parse.parse(requestEntityBaseResult.getData().getCertExpireDate()));
                                    date = startDate + "-" + endDate;
                                    String startDate1 = parse.format(parse1.parse(requestEntityBaseResult.getData().getCertStateDate()));
                                    String endDate1 = parse.format(parse1.parse(requestEntityBaseResult.getData().getCertExpireDate()));
                                    view.showOCRValidity(date);

                                } catch (Exception e) {
                                    Log.e("IDCardAuthPresenter", e.getMessage());
                                }
                                idCardEntity.setUsername(requestEntityBaseResult.getData().getUsername());
                                idCardEntity.setIdCard(requestEntityBaseResult.getData().getIdCard());
                                idCardEntity.setCertExpireDate(requestEntityBaseResult.getData().getCertExpireDate());
                                idCardEntity.setCertStateDate(requestEntityBaseResult.getData().getCertStateDate());
                                idCardEntity.setFaceUrl(requestEntityBaseResult.getData().getFaceUrl());
                                idCardEntity.setBackUrl(requestEntityBaseResult.getData().getBackUrl());
                            }
                        } else {
                            view.enshowInfo();
                        }


                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        view.dismissLoading();
                    }
                });
    }

    @Override
    public void commint() {
        String start = idCardEntity.getCertStateDate();
        String end = idCardEntity.getCertExpireDate();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        try {
            Date fomatDate1 = sdf.parse(start);
            Date fomatDate2 = sdf.parse(end);
            int result = fomatDate2.compareTo(fomatDate1);
            //如果日期相等返回0
            if (result == 0) {
                view.showToast("开始时间与结束时间一致！");
            } else if (result < 0) {
                //小于0，参数date1就是在date2之后
                view.showToast("开始时间大于结束时间!");
            } else {
                //大于0，参数date1就是在date2之前
                view.showLoading("正在提交");
                RealNameModel.ICcardcommit(this.idCardEntity)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<BaseResult>() {
                                       @Override
                                       public void accept(BaseResult baseResult) throws Exception {
                                           view.dismissLoading();
                                           if (baseResult.businessLogicSuccess()) {
                                               view.commitSuccess(idCardEntity.getUsername());
                                           } else {
                                               view.showToast(baseResult.getMessage());
                                               view.showEncommit();
                                           }

                                       }
                                   },
                                new Consumer<Throwable>() {
                                    @Override
                                    public void accept(Throwable throwable) throws Exception {
                                        view.dismissLoading();
                                        view.showToast(throwable.getMessage());
                                    }
                                });
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }


    }

    @Override
    public void onDestroy() {
        for (Disposable disposable : disposables) {
            if (disposable != null) {
                disposable.dispose();
            }
        }
    }
}